package uk.ac.tees.aetoolkit;

import java.util.Calendar;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.AlertDialog;
import android.app.PendingIntent;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TimePicker;
import android.widget.Toast;

/**
 * This class is used when the user picks 'Add Alarm' from the alarm class, it
 * adds an alarm to the shared preferences as well as making a pending intent
 * with a calendar object.
 * 
 * @author Sohail Rahman, Mark Williamson, Robert Sheffield
 * 
 */
public class AddAlarm extends Activity {

	/**
	 * Boolean variable set to true if user wants math question on wake up.
	 */
	private Boolean mathQ = false;
	/**
	 * Boolean variable set to true if user wants weather on wake up.
	 */
	private Boolean weather = false;
	/**
	 * Context variable set to this 'AddAlarm'.
	 */
	private Context context = this;
	/**
	 * An instance of a calendar.
	 */
	private Calendar cal;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.layout_addalarm);
		handleButtonEvent();
	}

	/**
	 * Method used to handle what happens when the user clicks 'set alarm'
	 */
	public void handleButtonEvent() {
		final EditText aDescription = (EditText) findViewById(R.id.aDescription);
		// Used for when the user has finished entering the data for the alarm.
		Button buttonstart = (Button) findViewById(R.id.button1);
		buttonstart.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TimePicker object to get hour/minute user has chosen.
				TimePicker tp = (TimePicker) findViewById(R.id.timePicker1);
				Calendar calendar = Calendar.getInstance();
				calendar.get(Calendar.HOUR_OF_DAY);
				calendar.get(Calendar.MINUTE);
				// Gets an instance of calculator set to the current time.
				Calendar calNow = Calendar.getInstance();
				cal = (Calendar) calNow.clone();
				// Sets the time to the time specified by the user.
				cal.set(Calendar.HOUR_OF_DAY, tp.getCurrentHour());
				cal.set(Calendar.MINUTE, tp.getCurrentMinute());
				cal.set(Calendar.SECOND, 0);
				cal.set(Calendar.MILLISECOND, 0);
				// Sets string display to what the user will see.
				final String display = tp.getCurrentHour() + ":"
						+ tp.getCurrentMinute() + " - "
						+ aDescription.getText().toString();
				// Creates an alarm manager.
				final AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
				// Loads shared preferences.
				final SharedPreferences prefs = getSharedPreferences(
						"pmd.aetoolkit", 0);
				// Alert dialog to select question or weather on wake up.
				AlertDialog.Builder alertDialog = new AlertDialog.Builder(
						AddAlarm.this);
				alertDialog.setTitle("Wake Up Options!");
				alertDialog.setMessage("Please pick an option");
				alertDialog.setPositiveButton("Weather",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,
									int which) {
								weather = true;
								// Starts AddAnAlarm method
								AddAnAlarm(prefs, alarmManager, context,
										display, aDescription.getText()
												.toString(), cal);
								Intent i = new Intent(AddAlarm.this,
										Alarm.class);
								startActivity(i);
							}
						});
				alertDialog.setNegativeButton("Math Question",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface d, int w) {
								mathQ = true;
								// Starts AddAnAlarm method
								AddAnAlarm(prefs, alarmManager, context,
										display, aDescription.getText()
												.toString(), cal);
								Intent i = new Intent(AddAlarm.this,
										Alarm.class);
								startActivity(i);
							}
						});
				alertDialog.show();
			}
		});
	}

	/**
	 * Method which is ran when an alarm is added, it puts required extras in
	 * which is needed by the dialog activity as well as creates a pending
	 * intent to trigger the alarm on the specified time.
	 * 
	 * @param prefs
	 *            passes through the current shared preferences.
	 * @param aManager
	 *            the current alarm manager is passed through.
	 * @param ctx
	 *            the context of the class which called it.
	 * @param disp
	 *            the display which is going to be shown to the user.
	 * @param desc
	 *            the description which the user entered (or 'voice').
	 * @param cal
	 *            the time the user specified.
	 */
	public void AddAnAlarm(SharedPreferences prefs, AlarmManager aManager,
			Context ctx, String disp, String desc, Calendar cal) {
		// Creates intent which will be started when the alarm goes off.
		Intent alarmIntent = new Intent(ctx, AlarmReceiver.class);
		// Puts the variables into the intent.
		alarmIntent.putExtra("DialogN", desc);
		alarmIntent.putExtra("Weather", weather);
		alarmIntent.putExtra("MathQ", mathQ);
		SharedPreferences.Editor editor = prefs.edit();
		int added = 0;
		boolean changed = false;
		// If an alarm is empty put a new one in (goes through alarms 0-4).
		for (int i = 0; i <= 4; i++) {
			if ((prefs.getString("alarm" + i, "") == "") && (changed == false)) {
				// Creates the pending intent.
				PendingIntent pendingAlarmIntent = PendingIntent.getService(
						ctx, i, alarmIntent, 0);
				aManager.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(),
						pendingAlarmIntent);
				editor.putString("alarm" + i, disp).commit();
				alarmIntent.putExtra("pos", i);
				changed = true;
			} else
				added++;
		}
		// If the alarms are full then inform the user.
		if (added == 5) {
			Toast.makeText(this.getBaseContext(),
					"Limit reached! Delete/Edit an exsisting alarm!",
					Toast.LENGTH_SHORT).show();
		}
	}

}